package com.moon;

import io.rong.imkit.RongIM;
import io.rong.imlib.model.UserInfo;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import cn.yueliangbaba.R;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.RequestParams;
import com.sys.Constants;
import com.sys.DemoApp;
import com.umeng.message.UmengRegistrar;
import com.umeng.update.UmengUpdateAgent;
import com.umeng.update.UmengUpdateListener;
import com.umeng.update.UpdateResponse;
import com.umeng.update.UpdateStatus;
import com.util.ImageLoaderHelper;
import com.util.MgqDataHandler;
import com.util.MgqRestClient;
import com.util.PreferencesUtils;
import com.util.ToastUtil;
import com.util.Utils;
import com.widget.CircleImageView;

import android.app.Activity;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MineActivity extends BaseActivity implements OnClickListener{
	Bitmap mBitmap = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_mine);

		findViewById(R.id.icon).setOnClickListener(this);
		findViewById(R.id.btn0).setOnClickListener(this);
		findViewById(R.id.btn1).setOnClickListener(this);
		findViewById(R.id.btn2).setOnClickListener(this);
		findViewById(R.id.btn4).setOnClickListener(this);
		findViewById(R.id.btn5).setOnClickListener(this);
		findViewById(R.id.btn6).setOnClickListener(this);
		findViewById(R.id.info).setOnClickListener(this);

		findViewById(R.id.next).setOnClickListener(this);
		((TextView)findViewById(R.id.version)).setText(getAppVersionName());
	}
	
	public void onResume()
	{
		super.onResume();
		setUsername();
	}
	
	public void setUsername()
	{
		JSONObject mMember = JSON.parseObject(PreferencesUtils.getString(this, "member"));
		
		JSONArray classes = new JSONArray(mMember.getJSONArray("classes"));
		boolean is_teacher = false;
		if(classes.size() > 0)
		{
			int count = classes.size();
			for(int i = 0; i < count; i++)
			{
				JSONObject classItem = classes.getJSONObject(i);
				if(classItem.getInteger("is_teacher") > 0) is_teacher = true;
			}
		}
		
		String path = mMember.getString("avatar_path");
		if(path != null && path.length() > 0) path = "http://120.27.129.233/ylbb/" + path;
		else path = "";
		
		if(is_teacher)
		{
			ImageLoaderHelper.displayImage(R.drawable.ic_teacher, (CircleImageView)findViewById(R.id.icon),path);
		}
		else
		{
			ImageLoaderHelper.displayImage(R.drawable.ic_family, (CircleImageView)findViewById(R.id.icon),path);
		}
		((TextView)findViewById(R.id.name)).setText(mMember.getString("username"));
	}

	@Override
	public void onClick(View arg0) {
		int viewId = arg0.getId();
		switch(viewId)
		{
		case R.id.info:
		{
			JSONObject member = JSON.parseObject(PreferencesUtils.getString(this, "member"));
			Intent intent = new Intent(this,PersonInfoActivity.class);
			intent.putExtra("name", member.getString("username"));
			intent.putExtra("userId",PreferencesUtils.getString(this, "userId"));
			intent.putExtra("flag", 0);
			startActivity(intent);
		}
			break;
		
		case R.id.next:
			showQuerySearch();
			break;
			
		case R.id.icon:
			showImagePicker();
			break;
			
		case R.id.btn0:
			startActivity(new Intent(this,ModifyUserActivity.class));
			break;
			
		case R.id.btn1:
			startActivity(new Intent(this,AboutActivity.class));
			break;

		case R.id.btn2:
			startActivity(new Intent(this,SettingsActivity.class));
			break;
			
		case R.id.btn6:
			startActivity(new Intent(this,MemberCenterActivity.class));
			break;
			
		case R.id.btn4:
		{
			Intent intent = new Intent(this,UserDisActivity.class);
			intent.putExtra("userId", PreferencesUtils.getString(this, "userId"));
			startActivity(intent);	
		}
		break;
		
		case R.id.btn5:
		{
			UmengUpdateAgent.setUpdateAutoPopup(false);
			UmengUpdateAgent.setUpdateListener(new UmengUpdateListener() {
				@Override
				public void onUpdateReturned(int arg0, UpdateResponse arg1) {
					switch (arg0) {
					case UpdateStatus.Yes: // has update
						UmengUpdateAgent.showUpdateDialog(MineActivity.this, arg1);
						break;
					case UpdateStatus.No: // has no update
						Toast.makeText(MineActivity.this, "没有更新", Toast.LENGTH_SHORT).show();
						break;
					case UpdateStatus.NoneWifi: // none wifi
						Toast.makeText(MineActivity.this, "没有wifi连接， 只在wifi下更新", Toast.LENGTH_SHORT).show();
						break;
					case UpdateStatus.Timeout: // time out
						Toast.makeText(MineActivity.this, "超时", Toast.LENGTH_SHORT).show();
						break;
					}
				}});
			UmengUpdateAgent.update(this);
		}
			break;
		}
	}
	
	void showImagePicker()
	{
		final Dialog mDialog = new Dialog(this, R.style.Dialog_Fullscreen);
		
		OnClickListener listen = new OnClickListener()
		{
			@Override
			public void onClick(View arg0) {
				if(arg0.getId() == R.id.cancel) mDialog.dismiss();
				else if(arg0.getId() == R.id.pic)
				{
					mDialog.dismiss();
					Intent getAlbum = new Intent(Intent.ACTION_GET_CONTENT);
					getAlbum.setType("image/*");
					startActivityForResult(getAlbum, 10);
				}
				else
				{
					mDialog.dismiss();
					try
					{
						startActivityForResult(new Intent("android.media.action.IMAGE_CAPTURE"), 11);
					}
					catch(Exception e)
					{
						ToastUtil.showToastWithAlertPic("您还没有授权");
					}
				}
			}
		};

		mDialog.setContentView(R.layout.dialog_img_choose);
		mDialog.findViewById(R.id.camera).setOnClickListener(listen);
		mDialog.findViewById(R.id.pic).setOnClickListener(listen);
		mDialog.findViewById(R.id.cancel).setOnClickListener(listen);
		mDialog.show();
	}

	private File mPhotoFile;
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (data == null)
			return;

		Bitmap bitmap = null;
		if (resultCode == Activity.RESULT_OK) {
			if (requestCode == 11) {
				try
				{
					Uri uri = data.getData();
					if (uri != null) {
						bitmap = Utils.getImageThumbnail(uri.getPath(),240,240);
					}
				}catch(Exception e){}

				if (bitmap == null) {
					try{
						Bundle bundle = data.getExtras();
						if (bundle != null) {
							bitmap = (Bitmap) bundle.get("data");
						}
					}catch(Exception e){}
				}
			} else if (requestCode == 10) {
				try {
					Uri uri = data.getData();
					
					ContentResolver cr = this.getContentResolver();
					Utils.write2File(cr.openInputStream(uri));
					
					bitmap = Utils.getImageThumbnail(Constants.PIC_PATH_TMP, 240, 240);//BitmapFactory.decodeStream(cr.openInputStream(uri));
				} catch (Exception e) {
					e.printStackTrace();
				}    
			}

			if (bitmap == null)
				return;
			
			if(mBitmap != null)
			{
				mBitmap.recycle();
				mBitmap = null;
			}
			
			mBitmap = bitmap;
			
			mPhotoFile = new File(Constants.PIC_PATH);// 将要保存图片的路径
			mPhotoFile.deleteOnExit();
			try {
				BufferedOutputStream bos = new BufferedOutputStream(
						new FileOutputStream(mPhotoFile));
				mBitmap.compress(Bitmap.CompressFormat.JPEG, 50, bos);
				bos.flush();
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

			sendHttpImgRequest();
		}
	}
	
	protected void onDestroy()
	{
		super.onDestroy();
		if(mBitmap != null)
		{
			mBitmap.recycle();
			mBitmap = null;
		}
	}
	
	private void sendRequest() {
		MgqDataHandler loginHandler = new MgqDataHandler(this, false, false) {
			@Override
			public void onSuccess(String response) {
				JSONObject ruser = JSON.parseObject(response);
				if (ruser.getString("statusCode").equals("0")) {
					JSONObject member = ruser.getJSONObject("member");
					
					PreferencesUtils.putString(MineActivity.this, "member", JSON.toJSONString(member));
					PreferencesUtils.putString(MineActivity.this, "classes", JSON.toJSONString(member.getJSONArray("classes")));
					PreferencesUtils.putString(MineActivity.this, "children", JSON.toJSONString(member.getJSONArray("children")));
					
					String path = member.getString("avatar_path");
					setUsername();
					RongIM.getInstance().refreshUserInfoCache(new UserInfo(member.getString("id"),
							"我",Uri.parse("http://120.27.129.233/ylbb/" + path)));
				}
				else
				{
					ToastUtil.showToastWithAlertPic(ruser.getString("message"));
				}
			}
			
			@Override
			public void onFailure(Throwable ble) {
				super.onFailure(ble);
				ToastUtil.showToastWithAlertPic("网络状况不佳，请稍后重试...");
			}
		};
		
		RequestParams params = new RequestParams();
		params.put("phonenumber", PreferencesUtils.getString(this, "username"));
		params.put("password", PreferencesUtils.getString(this, "password"));
		params.put("android_token", UmengRegistrar.getRegistrationId(this));//ios_token
		MgqRestClient.get("member_login", params, loginHandler);
	}
	
	private void sendHttpImgRequest() {
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				JSONObject ruser = JSON.parseObject(response);

				if (ruser.getString("statusCode").equals("0")) {
					((ImageView) findViewById(R.id.icon)).setImageBitmap(mBitmap);
					MainPageActivity.mMainPageActivity.autoRefresh();
					sendRequest();
				}
				else
				{
					ToastUtil.showToastWithAlertPic(ruser.getString("message"));
				}
			}
			
			@Override
			public void onFailure(Throwable ble) {
				super.onFailure(ble);
				ToastUtil.showToastWithAlertPic("网络状况不佳，请稍后重试...");
			}
		};

		RequestParams params = new RequestParams();
		params.put("id", PreferencesUtils.getString(this, "userId"));
		try {
			params.put("avatar", mPhotoFile);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		MgqRestClient.post("update_profile", params, loginHandler);
	}
	
	void showQuerySearch() {
		final Dialog mDialog = new Dialog(this, R.style.Dialog_Fullscreen);
		mDialog.setContentView(R.layout.dialog_query);
		mDialog.findViewById(R.id.left).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						mDialog.dismiss();
					}
				});
		mDialog.findViewById(R.id.right).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						mDialog.dismiss();
						logout();
					}
				});
		((TextView) mDialog.findViewById(R.id.content))
				.setText("确定退出该帐号？");
		mDialog.show();
	}
	
	private void logout() {
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@SuppressWarnings("deprecation")
			@Override
			public void onSuccess(String response) {
				JSONObject ruser = JSON.parseObject(response);
				if (ruser.getString("statusCode").equals("0")) {

					PreferencesUtils.putString(MineActivity.this, "username", "");
					PreferencesUtils.putString(MineActivity.this, "password", "");
					PreferencesUtils.putString(MineActivity.this, "userId", "");
					PreferencesUtils.putString(MineActivity.this, "member", "{}");
					PreferencesUtils.putString(MineActivity.this, "classes", "[]");
					PreferencesUtils.putString(MineActivity.this, "children", "[]");
					
					RongIM.getInstance().disconnect(true);
					startActivity(new Intent(MineActivity.this,LoginActivity.class));
				}
				else 
				{
					ToastUtil.showToastWithAlertPic(ruser.getString("message"));
				}
			}

			@Override
			public void onFailure(Throwable ble) {
				super.onFailure(ble);
				ToastUtil.showToastWithAlertPic("网络状况不佳，请稍后重试...");
			}
		};
		
		RequestParams params = new RequestParams();
		params.put("id", PreferencesUtils.getString(this, "userId"));
		params.put("os", "android");
		MgqRestClient.get("member_logout", params, loginHandler);
	}
	
	private long exitTime = 0;
	public void exitApp() {
		if ((System.currentTimeMillis() - exitTime) > 2000) 
		{
			Toast.makeText(this, "再按一次退出 应用", Toast.LENGTH_SHORT).show();
			exitTime = System.currentTimeMillis();
		} 
		else
		{
			finish();
		}
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {// 捕捉返回键
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			exitApp();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	public String getAppVersionName() {  
		String versionName = "";  
		try {  
			// ---get the package info---  
			PackageManager pm = getPackageManager();  
			PackageInfo pi = pm.getPackageInfo(getPackageName(), 0);  
			versionName = pi.versionName;  
	        if (versionName == null || versionName.length() <= 0) {  
	            return "";  
	        }  
	    } catch (Exception e) {  
	    }  
	    return "V" + versionName;  
	}  
}
